<?php

namespace app\admin\controller\yungift\gift;

use addons\yungift\model\Activity;
use addons\yungift\model\GiftOrder;
use addons\yungift\model\Group;
use addons\yungift\library\Constant;
use app\admin\model\yungift\CardMain;
use app\admin\model\yungift\GiftMain;
use app\admin\model\yungift\GiftSpec;
use app\common\controller\Backend;
use think\Db;
use think\Exception;

/**
 * 礼品
 */
class Main extends Backend
{
    /**
     * @var GiftMain
     */
    protected $model;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new GiftMain();

        // 礼品类型
        $this->view->assign('typeList', $this->model::getTypeList());
        $this->assignconfig('typeList', $this->model::getTypeList());

        // 礼品状态
        $this->view->assign('statusList', $this->model::getStatusList());
        $this->assignconfig('statusList', $this->model::getStatusList());

        // 领取方式
        $this->view->assign('gainMethods', [
            GiftOrder::GAIN_METHOD_EXPRESS => ['name' => '快递邮寄', 'tip' => ''],
            GiftOrder::GAIN_METHOD_SELF    => ['name' => '线下领取', 'tip' => ''],
        ]);
    }

    /**
     * 查看
     */
    public function index()
    {
        $modelId = $this->request->request('model_id');
        $modelType = $this->request->request('model_type');
        if ($this->request->isAjax()) {
            // 重载查询条件
            $filter = $this->request->get('filter');
            $op = $this->request->get('op');
            list($filter, $op) = $this->formatFilterOp($filter, $op);

            $filterTmp = json_decode($filter, true);
            $opTmp = json_decode($op, true);
            $worth = '';
            $worthOp = '';
            if (isset($filterTmp['worth'])) {
                $worth = $filterTmp['worth'];
                $worthOp = $opTmp['worth'];
                unset($filterTmp['worth'], $opTmp['worth']);
                $filter = json_encode($filterTmp);
                $op = json_encode($opTmp);
            }
            $this->request->get(['filter' => $filter, 'op' => $op]);
            // 如果有价值查询时, 先到礼品表查询出礼品id，再到礼品规格表中查出礼品id
            // 最后进行交集后，放入后续where中使用in查询
            $giftIds = [];
            if (!empty($worth)) {
                $worthRange = explode(',', $worth);
                $worth1 = empty(trim($worthRange[0])) ? 0 : trim($worthRange[0]);
                $worth2 = empty(trim($worthRange[1])) ? 10000000 : trim($worthRange[1]);
                // 先查询礼品表数据
                $giftQuery = new GiftMain();
                if ($worthOp === 'BETWEEN') {
                    if (count($worthRange) === 2) {
                        $giftQuery = $giftQuery->where('worth', '>=', $worth1)
                                 ->where('worth', '<=', $worth2);
                    }
                } else {
                    $giftQuery = $giftQuery->where('worth', $worthOp, $filter['worth']);
                }
                $giftIds = $giftQuery->column('id');
                // 到礼品规格表中查询
                $specQuery = new GiftSpec();
                if ($worthOp === 'BETWEEN') {
                    if (count($worthRange) === 2) {
                        $specQuery = $specQuery->where('worth', '>=', $worth1)
                                 ->where('worth', '<=', $worth2);
                    }
                } else {
                    $specQuery = $specQuery->where('worth', $worthOp, $filter['worth']);
                }
                $specGiftIds = [];
                $specGiftRows = $specQuery->select();
                foreach ($specGiftRows as $s) {
                    if (!in_array($s->gift_id, $specGiftIds)) {
                        $specGiftIds[] = $s->gift_id;
                    }
                }
                if (!empty($specGiftIds)) {
                    $giftIds = array_merge($giftIds, $specGiftIds);
                    $giftIds = array_unique($giftIds);
                }
                // var_dump($giftIds);
                // exit;
            }

            // 通用查询条件
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $query = $this->model->where($where);
            if (!empty($giftIds)) {
                $query = $query->where('id', 'in', $giftIds);
            }
            $list = $query->order($sort, $order)->limit($offset, $limit)->paginate($limit);
            $items = $list->items();
            $foreverTime = strtotime(Constant::FOREVER_DATE);
            foreach ($items as &$item) {
                if ($item->end_time == $foreverTime) {
                    $item->end_time = 0;
                }
            }
            $result = array(
                'total' => $list->total(),
                'rows'  => $items,
            );

            return json($result);
        }

        $this->assignconfig('modelId', $modelId);
        $this->assignconfig('modelType', $modelType);
        $this->assignconfig('chooseList', [1 => '已选择']);

        // 活动列表
        $activityList = Activity::getOptionList();
        $this->view->assign('activityList', $activityList);
        $this->assignconfig('activityList', $activityList);

        // 礼卡列表
        $cardList = CardMain::getOptionList();
        $this->view->assign('cardList', $cardList);
        $this->assignconfig('cardList', $cardList);

        // 分组列表
        $groupList = Group::getTreeList();
        $groupMap = ['0' => '未分组'];
        foreach ($groupList as $item) {
            $groupMap[$item['id']] = $item['name'];
        }
        $this->view->assign('groupMap', $groupMap);
        $this->assignconfig('groupMap', $groupMap);

        return $this->view->fetch();
    }

    /**
     * 格式化查询条件
     *
     * @param $filter
     * @param $op
     * @return array
     */
    private function formatFilterOp($filter, $op)
    {
        $filter = json_decode($filter, true);
        $op = json_decode($op, true);
        if (array_key_exists('activityId', $filter)) {
            $filter['activity_ids'] = $filter['activityId'];
            $op['activity_ids'] = 'find_in_set';
            unset($filter['activityId'], $op['activityId']);
        }
        if (array_key_exists('cardId', $filter)) {
            $filter['card_ids'] = $filter['cardId'];
            $op['card_ids'] = 'find_in_set';
            unset($filter['cardId'], $op['cardId']);
        }
        if (array_key_exists('choose', $filter)) {
            if ($filter['choose'] == 1) {
                $modelId = $this->request->request('model_id');
                $modelType = $this->request->request('model_type');
                if ($modelType === 'activity') {
                    $filter['activity_ids'] = $modelId;
                    $op['activity_ids'] = 'find_in_set';
                } elseif ($modelType === 'card') {
                    $filter['card_ids'] = $modelId;
                    $op['card_ids'] = 'find_in_set';
                }
            }
            unset($filter['choose'], $op['choose']);
        }
        if (array_key_exists('groupId', $filter)) {
            if ($filter['groupId']) {
                $filter['group_ids'] = Group::getRelationIds($filter['groupId']);
            } else {
                $filter['group_ids'] = 0;
            }
            $op['group_ids'] = 'find_in_set';
            unset($filter['groupId'], $op['groupId']);
        }

        return [json_encode($filter), json_encode($op)];
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if (isset($params['gain_methods'])) {
                $params['gain_methods'] = implode(',', $params['gain_methods']);
            }
            // 判断如果填写的截止时间为空时，默认一个大的时间
            if (empty($params['end_time'])) {
                $params['end_time'] = Constant::FOREVER_DATE;
            }
            $this->request->post(['row' => $params]);
        } else {
            $this->assignconfig('groupTreeList', Group::getTreeSelect());
        }
        
        return parent::add();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model::get($ids);
        if (! $row) {
            $this->error(__('No Results were found'));
        }

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if (isset($params['gain_methods'])) {
                $params['gain_methods'] = implode(',', $params['gain_methods']);
            }
            // 判断如果填写的截止时间为空时，默认一个大的时间
            if (empty($params['end_time'])) {
                $params['end_time'] = Constant::FOREVER_DATE;
            }
            $this->request->post(['row' => $params]);
        } else {
            $groupIds = $row->group_ids ? explode(',', $row->group_ids) : [];
            $this->assignconfig('groupTreeList', Group::getTreeSelect($groupIds));
        }

        return $this->_edit($ids);
    }

    /**
     * 绑定活动或礼卡
     */
    public function bind()
    {
        $params = $this->request->post();
        if ($params) {
            try {
                $giftId = $params['ids'];
                $action = $params['action'];
                parse_str($params['params'], $values);
                $modelId = $values['model_id'];
                $modelType = $values['model_type'];
                if ($modelType === 'activity') {
                    if (! Activity::get($modelId)) {
                        $this->error('活动不存在');
                    }
                } elseif ($modelType === 'card') {
                    if (! CardMain::get($modelId)) {
                        $this->error('礼卡不存在');
                    }
                } else {
                    $this->error('model_type不对');
                }
                if (! $gift = GiftMain::get($giftId)) {
                    $this->error('礼品不存在');
                }
                $modelField = '';
                if ($modelType === 'activity') {
                    $modelField = 'activity_ids';
                } elseif ($modelType === 'card') {
                    $modelField = 'card_ids';
                }
                $modelIds = $gift->getData($modelField) ? explode(',', $gift->getData($modelField)) : [];
                if ($action === 'yes') {
                    $modelIds[] = $modelId;
                    $modelIds = array_unique($modelIds);
                } elseif ($action === 'no') {
                    $modelIds = array_filter($modelIds, function ($value) use ($modelId) {
                        return $value != $modelId;
                    });
                } else {
                    $this->error('action不对');
                }
                $gift->data([$modelField => implode(',', $modelIds)]);
                $gift->save();
            } catch (Exception $e) {
                $this->error($e->getMessage());
            }
            $this->success();
        }
        $this->error(__('Parameter %s can not be empty', ''));
    }

    private function _edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            if ($row->end_time == strtotime(Constant::FOREVER_DATE)) {
                $row->end_time = 0;
            }
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }
}
